//
//  XMGPictureBrowserController.m
//  微博
//
//  Created by zxy on 2018/12/26.
//  Copyright © 2018 zxy. All rights reserved.
//

#import "XMGPictureBrowserController.h"
#import "XMGBrowserCell.h"
static NSString *const browserCellId = @"browserCellId";
@interface XMGPictureBrowserController ()<PictureBrowserDissmissDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *browserCollectionView;

@end

@implementation XMGPictureBrowserController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.browserCollectionView registerClass:[XMGBrowserCell class] forCellWithReuseIdentifier:browserCellId];
}

//关闭
- (IBAction)closeBtnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存图片
- (IBAction)saveBtnClick:(UIButton *)sender {
    //1.拿到对应图片cell
    NSIndexPath *indexPh = [self.browserCollectionView indexPathsForVisibleItems].lastObject;
    XMGBrowserCell *cell= (XMGBrowserCell *)[self.browserCollectionView cellForItemAtIndexPath:indexPh];
    //2.获取cell上图片
    UIImage *browserImage = cell.browserImageView.image;
    //3.保存到相册
    UIImageWriteToSavedPhotosAlbum(browserImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMaximumDismissTimeInterval:0.5];
    if(error == nil){
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }else{
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }
}

-(void)dealloc{
    NSLog(@"控制器已经销毁了");
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.pictureModel.big_picUrls.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return [UIScreen mainScreen].bounds.size;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XMGBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:browserCellId forIndexPath:indexPath];
    NSString *url = self.pictureModel.big_picUrls[indexPath.item];
    cell.pictureUrl = url;
    cell.delegate = self;
    return cell;
}

#pragma mark -关闭图片浏览器
-(void)pictureBrowserDissmiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}



@end
